package br.com.concordia.broker;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import br.com.bb.broker.Broker;
import br.com.bb.stock.Stock;

public class BrokerConcordia implements Broker {
	private String driver;
	private String url;
	private Properties config;
	
	public BrokerConcordia() {
		this.driver          = "org.apache.derby.jdbc.ClientDriver";
		//this.url             = "jdbc:derby://192.168.1.2:1527/Database/BrokerConcordiaDB;traceFile=trace.log";
		this.url             = "jdbc:derby://localhost:1527/Database/BrokerConcordiaDB;traceFile=trace.log";
		try {
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.config = new Properties();
		config.setProperty("proxool.maximum-connection-count", "100");
	}


	@Override
	public boolean pursharseOrder(String investorCode, Stock stock,int quantity, double orderPrice) {
		Connection conn = null;
		PreparedStatement psInsert = null;
		System.out.println("===>> Concordia: Order received " + investorCode + " - " + stock.getCode() + " - " + quantity + " - " + orderPrice);
		try {
			conn = this.getConnection();
			// System.out.println("Connected to database " + DB_CONNECTION_URL);
			psInsert = conn
			.prepareStatement("INSERT INTO ORD_ORDER (ORD_INVESTORCODE, ORD_STOCK, ORD_QUANTITY, ORD_PRICE) VALUES (?, ?, ?, ?)");

			psInsert.setString(1, investorCode);
			psInsert.setString(2, stock.getCode());
			psInsert.setInt(3, quantity);
			psInsert.setDouble(4, orderPrice);
			
			psInsert.executeUpdate();

		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		} finally {
			if (psInsert != null) {
				try {
					psInsert.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		}

		return true;
	}
	
	private Connection getConnection() throws SQLException {
		// return cpds.getConnection();
		return DriverManager.getConnection("proxool.agencia:" + driver + ":" + url,config);
	}
	
	public static void main(String args[]) {
		BrokerConcordia broker = new BrokerConcordia();
		broker.pursharseOrder("M345656", Stock.PETR3, 30, 10.5);
	}
}
